package com.zhentao.controller;

import com.zhentao.common.Result;
import com.zhentao.entity.User;
import com.zhentao.service.UserService;
import com.zhentao.vo.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = "*")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 获取用户信息
     * @param userId 用户ID（必传）
     * @return 用户信息
     */
    @GetMapping("/info")
    public Result<UserInfoVO> getUserInfo(@RequestParam Long userId) {
        System.out.println("=== UserController.getUserInfo 接收请求 ===");
        System.out.println("接收到的用户ID: " + userId + " (类型: " + userId.getClass().getSimpleName() + ")");
        
        try {
            // 验证用户ID
            if (userId == null || userId <= 0) {
                System.out.println("❌ 用户ID无效: " + userId);
                return Result.error("用户ID无效");
            }
            
            System.out.println("✅ 用户ID验证通过，开始查询用户信息...");
            UserInfoVO vo = userService.getUserInfo(userId);
            
            if (vo != null) {
                System.out.println("✅ 查询成功，用户: " + vo.getNickname() + " (ID: " + vo.getUserId() + ")");
            } else {
                System.out.println("❌ 查询结果为null");
            }
            
            return Result.success(vo);
        } catch (RuntimeException e) {
            System.err.println("❌ RuntimeException: " + e.getMessage());
            e.printStackTrace();
            return Result.error(e.getMessage());
        } catch (Exception e) {
            System.err.println("❌ Exception: " + e.getMessage());
            e.printStackTrace();
            return Result.error("获取用户信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新用户基本信息（包括出生日期等）
     * @param user 用户基本信息对象
     * @return 更新结果
     */
    @PutMapping("/basic")
    public Result<String> updateUserBasicInfo(@RequestBody User user) {
        try {
            if (user.getUserId() == null) {
                return Result.error("用户ID不能为空");
            }
            
            Boolean success = userService.updateUserBasicInfo(user);
            if (success) {
                return Result.success("用户信息更新成功", "success");
            } else {
                return Result.error("用户信息更新失败");
            }
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("用户信息更新失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新用户单个基本字段
     * @param userId 用户ID
     * @param fieldName 字段名
     * @param fieldValue 字段值
     * @return 更新结果
     */
    @PutMapping("/basic/field")
    public Result<String> updateUserBasicField(
            @RequestParam Long userId,
            @RequestParam String fieldName,
            @RequestParam String fieldValue) {
        try {
            User user = new User();
            user.setUserId(userId);
            
            // 根据字段名设置值
            switch (fieldName) {
                case "nickname":
                    user.setNickname(fieldValue.isEmpty() ? null : fieldValue);
                    break;
                case "phone":
                    user.setPhone(fieldValue.isEmpty() ? null : fieldValue);
                    break;
                case "email":
                    user.setEmail(fieldValue.isEmpty() ? null : fieldValue);
                    break;
                case "gender":
                    if (fieldValue.isEmpty()) {
                        user.setGender(null);
                    } else {
                        try {
                            user.setGender(Integer.valueOf(fieldValue));
                        } catch (NumberFormatException e) {
                            return Result.error("性别值必须是有效的数字");
                        }
                    }
                    break;
                case "birthDate":
                    if (fieldValue.isEmpty()) {
                        user.setBirthDate(null);
                    } else {
                        try {
                            user.setBirthDate(java.time.LocalDate.parse(fieldValue));
                        } catch (Exception e) {
                            return Result.error("出生日期格式错误，请使用YYYY-MM-DD格式");
                        }
                    }
                    break;
                case "avatarUrl":
                    user.setAvatarUrl(fieldValue.isEmpty() ? null : fieldValue);
                    break;
                default:
                    return Result.error("不支持的字段: " + fieldName);
            }
            
            Boolean success = userService.updateUserBasicInfo(user);
            if (success) {
                return Result.success("字段更新成功", "success");
            } else {
                return Result.error("字段更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("字段更新失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户年龄
     * @param userId 用户ID
     * @return 用户年龄
     */
    @GetMapping("/age")
    public Result<Integer> getUserAge(@RequestParam Long userId) {
        try {
            Integer age = userService.calculateUserAge(userId);
            return Result.success("获取年龄成功", age);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取年龄失败: " + e.getMessage());
        }
    }
    
    /**
     * 健康检查接口
     * @return 服务状态
     */
    @GetMapping("/health")
    public Result<String> healthCheck() {
        try {
            return Result.success("Essential服务运行正常", "healthy");
        } catch (Exception e) {
            return Result.error("服务异常: " + e.getMessage());
        }
    }
}

